<template>
  <a-modal
    :width="900"
    v-model:visible="state.apiSelectDia"
    :title="t('选择接口')"
    :maskClosable="false"
    :bodyStyle="state.modalBodyStyle"
    @ok="handleSubmit"
    @cancel="handleClose"
  >
    <div class="box-left">
      <div class="title">{{ t('接口分类') }}</div>
      <a-tree
        v-model:expandedKeys="state.expandedKeys"
        v-model:selectedKeys="state.selectedKeys"
        :tree-data="state.interfaceTreeData"
        :fieldNames="state.fieldNames"
        @select="selectTree"
      />
    </div>
    <div class="box-right">
      <div class="title">{{ t('接口列表') }}</div>
      <a-row :gutter="12" style="padding: 10px 0; border-top: 1px solid #f0f0f0">
        <a-col :span="8">
          <a-input v-model:value="state.searchText" :placeholder="t('输入搜索关键字')" allowClear />
        </a-col>
        <a-col>
          <a-button type="primary" @click="handleSearch"> {{ t('搜索') }} </a-button>
        </a-col>
      </a-row>
      <a-table
        :dataSource="state.interfaceDataSource"
        :columns="state.apiConfigColumns"
        rowKey="id"
        :pagination="state.paginationProps"
        :row-selection="{
          selectedRowKeys: state.selectedRowKeys,
          onChange: onSelectChange,
          type: 'radio',
        }"
        :customRow="customRow"
        :scroll="{ y: '200px' }"
      />
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import { onMounted, reactive, watch } from 'vue';
  import { ColumnProps } from 'ant-design-vue/lib/table/Column';
  import { getInterfaceTree, getInterfaceList } from '/@/api/system/interface/index';
  import { InterfaceList } from '../interface';
  import { getInterfaceInfo } from '/@/api/system/interface/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const props = defineProps({
    apiSelectDialog: { type: Boolean },
    selectedApiId: { type: String },
  });
  const emit = defineEmits(['update:apiSelectDialog', 'update:selectedApiId', 'success']);
  const state = reactive({
    apiSelectDia: props.apiSelectDialog,
    interfaceTreeData: [] as any[],
    expandedKeys: [] as string[],
    selectedKeys: [] as string[],
    interfaceList: [] as InterfaceList[], //接口列表全部
    interfaceListSearch: [] as InterfaceList[], //接口列表搜索全部
    interfaceDataSource: [] as InterfaceList[], //接口列表分页
    selectedRowKeys: [] as string[],
    searchText: '' as string,
    isSearch: false,
    fieldNames: { children: 'children', title: 'name', key: 'id' },
    modalBodyStyle: {
      display: 'flex',
      padding: '15px 15px 10px 10px',
      minHeight: '400px',
    },
    apiConfigColumns: [
      {
        key: 'name',
        title: t('接口名称'),
        dataIndex: 'name',
        width: 300,
      },
      {
        key: 'path',
        title: t('接口地址'),
        dataIndex: 'path',
      },
    ] as ColumnProps[],
    paginationProps: {
      current: 1,
      total: 0,
      pageSize: 10,
      showQuickJumper: true,
      showSizeChanger: true,
      onChange: (page: number) => getInterfacePage(page),
      onShowSizeChange: (current: number, pageSize: number) => {
        state.paginationProps.pageSize = pageSize;
        getInterfacePage(current);
      },
    },
    interfaceInfo: [
      {
        key: '1',
        title: 'Query Params',
        tableInfo: [],
      },
      {
        key: '2',
        title: 'Header',
        tableInfo: [],
      },
      {
        key: '3',
        title: 'Body',
        tableInfo: [],
      },
    ],
    configInfo: {
      path: '',
      method: '',
      apiId: '',
      apiParams: [] as any[],
      script: '',
    },
  });

  onMounted(() => {
    getInterfaceTreeData();
  });
  watch(
    () => props.selectedApiId,
    (val) => {
      if (!!val) {
        state.selectedRowKeys.push(val);
      }
    },
    {
      immediate: true,
      deep: true,
    },
  );
  //获取左边树结构
  const getInterfaceTreeData = async () => {
    state.interfaceTreeData = await getInterfaceTree();
    //默认展示第一个接口分类的列表
    if (state.interfaceTreeData.length && state.interfaceTreeData[0].id) {
      const id = state.interfaceTreeData[0].id;
      state.selectedKeys.push(id);
      state.expandedKeys.push(id);
      selectTree(state.selectedKeys);
    }
  };
  //获取右边接口列表
  const selectTree = async (selectedKeys: string[], e?) => {
    state.isSearch = false;
    if (!selectedKeys.length) state.selectedKeys.push(e.node.dataRef.id);
    const groupId = selectedKeys[selectedKeys.length - 1];
    const data = await getInterfaceList({ groupId });
    //清空接口列表
    state.interfaceList = [];
    data.map((item: any) => {
      state.interfaceList.push({
        id: item.id,
        name: item.name,
        path: item.path,
      });
    });
    getInterfacePage(1);
  };
  //展示右边接口列表（分页）
  const getInterfacePage = (page) => {
    const size = state.paginationProps.pageSize;
    const startIndex = (page - 1) * size;
    const endIndex = page * size;

    const list = state.isSearch ? state.interfaceListSearch : state.interfaceList;

    state.paginationProps.current = page;
    state.paginationProps.total = list.length;
    state.interfaceDataSource = list.slice(startIndex, endIndex);
  };
  const handleSearch = () => {
    state.isSearch = true;
    state.interfaceListSearch = state.interfaceList.filter((item: InterfaceList) => {
      const hasKeywords = Object.values(item).find((val: string, index: number) => {
        //index!==0 id不参与搜索
        return index !== 0 && val.indexOf(state.searchText) !== -1;
      });
      return hasKeywords;
    });

    getInterfacePage(1);
  };

  const customRow = (record: InterfaceList) => {
    return {
      onClick: () => {
        let selectedRowKeys = [...state.selectedRowKeys];
        if (selectedRowKeys.indexOf(record.id) >= 0) {
          let index = selectedRowKeys.indexOf(record.id);
          selectedRowKeys.splice(index, 1);
        } else {
          selectedRowKeys = [record.id];
        }
        state.configInfo.apiId = selectedRowKeys[0];
        state.selectedRowKeys = selectedRowKeys;
      },
    };
  };
  const onSelectChange = (rowKey: string[]) => {
    state.selectedRowKeys = rowKey;
    state.configInfo.apiId = rowKey[0];
  };
  const getInterfaceInfoById = async (id) => {
    const data = await getInterfaceInfo({ id });
    state.interfaceInfo[0].tableInfo = data.parameters;
    state.interfaceInfo[1].tableInfo = data.headers;
    state.interfaceInfo[2].tableInfo = data.requestBodyDefinition?.children;
    state.configInfo.path = data.path;
    state.configInfo.method = data.method;
    state.configInfo.script = data.script;
    state.configInfo.apiParams = state.interfaceInfo;
    emit('success', state.configInfo);
  };
  const handleSubmit = async () => {
    if (!!state.selectedRowKeys[0]) {
      await getInterfaceInfoById(state.selectedRowKeys[0]);
      emit('update:selectedApiId', state.selectedRowKeys[0]);
    }
    emit('update:apiSelectDialog', false);
  };
  const handleClose = () => {
    emit('update:apiSelectDialog', false);
  };
</script>
<style lang="less" scoped>
  .box-left {
    flex: 1;
  }

  .box-right {
    flex: 2;
  }

  .title {
    font-size: 16px;
    line-height: 18px;
    margin-bottom: 15px;
    padding-left: 6px;
    border-left: 6px solid #5e95ff;
  }

  :deep(.ant-tree) {
    padding: 10px 15px 0 0;
    border-top: 1px solid #f0f0f0;
  }

  :deep(.ant-tree-treenode),
  :deep(.ant-tree-node-content-wrapper) {
    width: 100%;
    height: 35px;
    line-height: 35px;
  }

  :deep(.ant-table-body) {
    height: 200px;
  }
</style>
